package com.jdjw.modules.thirdpost.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdjw.common.ResponseResult;
import com.jdjw.modules.thirdpost.mapper.BusProcureApplyMapper;
import com.jdjw.modules.thirdpost.param.*;
import com.jdjw.modules.thirdpost.result.BusProcureApply;
import com.jdjw.utils.CommonUtil;
import com.jdjw.utils.ConstantUtil;
import com.jdjw.utils.DateUtil;
import com.jdjw.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 村级采购基础表
 */
@Slf4j
@Service
public class BusProcureApplyServiceImpl extends ServiceImpl<BusProcureApplyMapper, BusProcureApply>
        implements IService<BusProcureApply> {

    @Autowired
    static BusProcureApplyMapper busProcureApplyMapper;

    @Autowired
    static ThirdPostExceptionServiceImpl thirdPostExceptionServiceImpl;

    @Resource
    public void setThirdPostExceptionServiceImpl(ThirdPostExceptionServiceImpl thirdPostExceptionServiceImpl) {
        BusProcureApplyServiceImpl.thirdPostExceptionServiceImpl = thirdPostExceptionServiceImpl;
    }

    @Resource
    public void setBusProcureApplyMapper(BusProcureApplyMapper busProcureApplyMapper) {
        BusProcureApplyServiceImpl.busProcureApplyMapper = busProcureApplyMapper;
    }


    public static void doPostSZyxzcmxbJiande(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 15;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 15;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 15;
        }
        try {
            //查询
            List<BusProcureApply> list = busProcureApplyMapper.selectCha(thirdPostInParm);
            if (list == null || list.size() < 1) {
                log.info("村级采购基础表数据库查询数据为0条");
                return;
            }
            if (list.size() > 3000) {
                Integer count = list.size() / 3000 + 1;
                Collection<Collection<BusProcureApply>> fgList = CommonUtil.subCollection(list, count);
                for (Collection<BusProcureApply> obj : fgList) {
                    sendData((List<BusProcureApply>) obj, url);
                }
            } else {
                sendData(list, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendData(List<BusProcureApply> obj, String url) throws ParseException {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (BusProcureApply a : obj) {
            BusProcureApplyParam param = new BusProcureApplyParam();
            param.setBiz_id(a.getId());
            param.setId(a.getId());
            param.setCwh(a.getCwhgxa());
            param.setCwhxzqh(CommonUtil.addZeroForNum(a.getOrgCode(), 16));
            param.setCgdw(a.getOrgName());
            param.setXmmc(a.getProcureName());
            param.setCgxmbm(a.getProcureCode());
            param.setLxrq(a.getProjectDate());
            param.setCglx(Integer.parseInt(a.getProcureType()));
            if (StringUtils.isNotBlank(a.getIsOpen())) {
                param.setSfgk(Integer.parseInt(a.getIsOpen()));//部分没有数据  是否公开招标
            } else {
                param.setSfgk(0);
            }
            param.setCgfs(Integer.parseInt(a.getProcureWay()));
//            param.setCgfs(1);//有6哥状态，但是他们的只有两个   解决方案：以他们状态一样的就对应一样，不一样的或者多出的就放到他们的‘其他’状态里
            param.setZbdlig(a.getBiddingAgency());
            param.setTyshxydm(a.getBiddingAgencyCode());
            //有些数据为null 可以为空
//            param.setKzjy(Double.parseDouble(a.getExpectAmount()));
            param.setKzjy(1.01);
            param.setCgwjfsrq(a.getPurchaseDocumentsIssueDate());// ke null
            param.setZbggrq(a.getTenderAnnouncementDate());// ke null
            param.setKbsj(a.getBidOpenTime());// ke null
//            param.setZbj(a.getBidPrice());
            //数据带有字符串
            if(StringUtils.isNotBlank(a.getConfirmPrice())){
                param.setZbj(Double.parseDouble(a.getConfirmPrice()));
            }
            param.setZj_type(a.getZjType());//1:单位 2:个人
            param.setWinnername(a.getSupplier());
            param.setZbdwxydm(a.getZbdwxydm());
//            param.setWinnerid();//数据库没有该字段
            if (StringUtils.isNotBlank(a.getProcureScop())) {
                if ("1".equals(a.getProcureScop()) && StringUtils.isNotBlank(a.getConfirmAmount())) {
                    param.setCgyfze(Double.parseDouble(a.getConfirmAmount()));
                }
                if ("2".equals(a.getProcureScop()) && StringUtils.isNotBlank(a.getAmountService())) {
                    param.setCgyfze(Double.parseDouble(a.getAmountService()));
                }
            }
            param.setOperator(a.getAgentPerson());
            param.setDel_flag(0);

            //转化为json字符串
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("返回: " + jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("村级采购基础表推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "doPostSZyxzcmxbJiande","村级采购基础表推送失败",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD,new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("村级采购基础表推送失败", result);
            }
        } else {
            log.info("村级采购基础表推送失败", "第三方返回空");
        }
    }


    /**
     * String -> date
     */
    public static Date stringDate(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            // 注意格式需要与上面一致，不然会出现异常
            if (StringUtils.isNotBlank(time)) {
                date = sdf.parse(time);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            //如果错误，返回昨天日期
            Date today = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dates = simpleDateFormat.format(today);
            stringDate(dates);
        }
        return date;
    }


    public static void BusCaigouhetong(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 18;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 18;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 18;
        }
        try {
            //查询
            List<BusProcureApply> list = busProcureApplyMapper.selectCha(thirdPostInParm);
            if (list == null || list.size() < 1) {
                log.info("采购合同编号数据库查询数据为0条");
                return;
            }
            if (list.size() > 3000) {
                Integer count = list.size() / 3000 + 1;
                Collection<Collection<BusProcureApply>> fgList = CommonUtil.subCollection(list, count);
                for (Collection<BusProcureApply> obj : fgList) {
                    sendDatatwo((List<BusProcureApply>) obj, url);
                }
            } else {
                sendDatatwo(list, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendDatatwo(List<BusProcureApply> obj, String url) {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (BusProcureApply a : obj) {
            BusProcureApplyEntParam param = new BusProcureApplyEntParam();
            param.setBiz_id(a.getId());
            param.setId(a.getId());
            param.setParent_id(a.getId());
            param.setCwh(a.getCwhgxa());
            param.setCwhxzqh(CommonUtil.addZeroForNum(a.getOrgCode(), 16));
            param.setCghtbh(a.getProcureContractNo());
            param.setCghtspr(a.getContractExaminer());
            param.setCghtqdsj(a.getConfirmDate());
            if (StringUtils.isNotBlank(a.getConfirmAmount())) {
                param.setCghtqdjg(Double.parseDouble(a.getConfirmAmount()));
            }
            param.setDel_flag(0);

            //转化为json字符串
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("返回: " + jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("采购合同编号推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "BusCaigouhetong", "采购合同编号数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("采购合同编号推送失败", result);
            }
        } else {
            log.info("采购合同编号推送失败", "第三方返回空");
        }
    }


    public static void BusCaigouleibie(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 19;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 19;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 19;
        }
        try {
            //查询
            List<BusProcureApply> list = busProcureApplyMapper.selectCha(thirdPostInParm);
            if (list == null || list.size() < 1) {
                log.info("采购类别数据库查询数据为0条");
                return;
            }
            if (list.size() > 3000) {
                Integer count = list.size() / 3000 + 1;
                Collection<Collection<BusProcureApply>> fgList = CommonUtil.subCollection(list, count);
                for (Collection<BusProcureApply> obj : fgList) {
                    sendDataThree((List<BusProcureApply>) obj, url);
                }
            } else {
                sendDataThree(list, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendDataThree(List<BusProcureApply> obj, String url) {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (BusProcureApply a : obj) {

            BusAssetApplyNeiRongParam param = new BusAssetApplyNeiRongParam();
            param.setBiz_id(a.getId());
            param.setId(a.getId());
            param.setParent_id(a.getId());
            param.setCwh(a.getCwhgxa());
            param.setCwhxzqh(CommonUtil.addZeroForNum(a.getOrgCode(), 16));
            param.setCghtbh(a.getProcureContractNo());
            //数据字典对不上，解决方案：服务类2  商品类1
            param.setCglb(Integer.parseInt(a.getProcureScop()));
            param.setCgnr(a.getProcureContent());
            if (StringUtils.isNotBlank(a.getConfirmNum())) {
                param.setCgsl(Integer.parseInt(a.getConfirmNum()));//not null
            }
            param.setCgdj(Double.parseDouble(a.getConfirmPrice()));//null?
            if (StringUtils.isNotBlank(a.getProcureScop())) {
                if ("1".equals(a.getConfirmAmount())) {
                    param.setCgzjey(Double.parseDouble(a.getConfirmAmount()));
                } else if ("2".equals(a.getConfirmAmount())) {
                    param.setCgzjey(Double.parseDouble(a.getAmountService()));
                }
            }
            param.setDel_flag(0);

            //转化为json字符串
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("返回: " + jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("采购类别推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "BusCaigouleibie", "采购类别数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("采购类别推送失败", result);
            }
        } else {
            log.info("采购类别推送失败", "第三方返回空");
        }
    }


    /**
     * 支付款数据
     */
    public static void BusZhifu(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 16;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 16;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 16;
        }
        try {
            //查询
            List<BusProcureApply> list = busProcureApplyMapper.selectCha(thirdPostInParm);
            if (list == null || list.size() < 1) {
                log.info("支付款数据库查询数据为0条");
                return;
            }
            if (list.size() > 3000) {
                Integer count = list.size() / 3000 + 1;
                Collection<Collection<BusProcureApply>> fgList = CommonUtil.subCollection(list, count);
                for (Collection<BusProcureApply> obj : fgList) {
                    sendzhifu((List<BusProcureApply>) obj, url);
                }
            } else {
                sendzhifu(list, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendzhifu(List<BusProcureApply> obj, String url) {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (BusProcureApply a : obj) {
            BusAssetApplyZhiFuParam param = new BusAssetApplyZhiFuParam();
            param.setBiz_id(a.getId());
            param.setId(a.getId());
            param.setParent_id(a.getId());
            param.setCwh(a.getCwhgxa());
            param.setCwhxzqh(CommonUtil.addZeroForNum(a.getOrgCode(), 16));
//            param.setFklb(0);//数据库没有字段
//            param.setZfkbm();//数据库没有字段
            if (StringUtils.isNotBlank(a.getSupplier())) {
                param.setSkdw(a.getSupplier());
            }
            param.setSkdwshxydm(a.getOrgCode());//需要用supplier关联bus_procure_apply_ent.name获取bus_procure_apply_ent.org_code
            if (StringUtils.isNotBlank(a.getPayCard())) {
                param.setFkpz(a.getPayCard());
            }
            param.setType(a.getZjType());//CASE WHEN LENGTH(supplier) < 15 THEN 2 ELSE 1 END
//            param.setCkryhzh("cs");//数据库没有字段
            param.setFkrq(a.getPayDate());
            if (StringUtils.isNotBlank(a.getPayAmount())) {
                param.setFkjey(Double.parseDouble(a.getPayAmount()));
            }
            param.setCwztmc(a.getPaySet());
            param.setFpsh(a.getInvoiceCard());
            param.setPzh(a.getPayCard());
            param.setDel_flag(0);

            //转化为json字符串
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("返回: " + jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("支付款推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "BusZhifu", "支付款数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("支付款推送失败", result);
            }
        } else {
            log.info("支付款推送失败", "第三方返回空");
        }
    }


}
